package com.fnst.caesar.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Servlet Filter implementation class Character_Filter
 */
public class Character_Filter implements Filter
{

	private FilterConfig config = null;
	private String encoding = null;
	/**
	 * Default constructor.
	 */
	public Character_Filter()
	{
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy()
	{
		// TODO Auto-generated method stub
		this.config = null;
		this.encoding = null;
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException
	{
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain
		if(this.config != null)
		{
			if(this.encoding != null)
			{
				request.setCharacterEncoding(encoding);		//if the encoding is set, then take the initial value
				response.setCharacterEncoding(encoding);
			}
			else
			{
				request.setCharacterEncoding("UTF-8");		//if the encoding is not set, then set default value UTF-8
				response.setCharacterEncoding("UTF-8");
			}
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException
	{
		// TODO Auto-generated method stub
		this.config = fConfig;
		this.encoding = config.getInitParameter("encoding");
	}

}
